<template>
  <div>
  <div class="per-learn-case">
    <el-button  class="back" type="text" icon="el-icon-arrow-left" @click="goBack">返回</el-button>
    <!-- 顶部导航 -->
    <div class="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>学情分析</el-breadcrumb-item>
        <el-breadcrumb-item>单个学生学情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 左侧学生列表 -->
    <div class="content">
      <div class="student-list">
        <div class="student-info-box">
          <div class="info-title">学生信息</div>
          <div class="student-info-item">
            <span class="info-label">姓名：</span>
            <span class="info-value">{{ studentName || '未知' }}</span>
          </div>
          <div class="student-info-item">
            <span class="info-label">学号：</span>
            <span class="info-value">{{ studentId || '未知' }}</span>
          </div>
          <div class="student-info-item">
            <span class="info-label">班级：</span>
            <span class="info-value">{{ studentClass || '未知' }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧学情详情 -->
      <div class="student-details">
        <div class="student-header">
          <h3>学科：{{ teacherSubjectName }}</h3>
        </div>
        
        <!-- 学生历次考试信息展示 -->
        <div v-if="examRecords && examRecords.length > 0" class="exam-records-section">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
            <h4>历次考试成绩</h4>
            <div>
              <el-button type="primary" size="small" @click="showAddExamDialog">添加考试记录</el-button>
              <el-button type="warning" size="small" @click="showEditExamDialog" :disabled="!selectedExam">修改考试记录</el-button>
                <!-- 删除删除考试记录按钮 -->
            </div>
          </div>
          <el-table
            :data="examRecords"
            border
            style="width: 100%"
            height="300"
            :header-cell-style="{background: '#f5f7fa', color: '#1b4380', fontWeight: 'bold'}"
            @current-change="handleExamRowChange"
          >
            <el-table-column prop="examName" label="考试名称" width="180"></el-table-column>
            <el-table-column prop="examTime" label="考试时间" width="120" :formatter="formatDate"></el-table-column>
            
            <!-- 只显示教师所教学科的成绩 -->
            <el-table-column v-if="teacherSubject === 'chinese'" prop="chinese" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="teacherSubject === 'math'" prop="math" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="teacherSubject === 'english'" prop="english" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="teacherSubject === 'politics'" prop="politics" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="teacherSubject === 'history'" prop="history" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="teacherSubject === 'geography'" prop="geography" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="teacherSubject === 'physics'" prop="physics" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="teacherSubject === 'chemistry'" prop="chemistry" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="teacherSubject === 'biology'" prop="biology" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            
              <el-table-column :prop="teacherSubject + '_remarks'" :label="teacherSubjectName + '备注'" min-width="200" show-overflow-tooltip></el-table-column>
          </el-table>
        </div>
        <div v-else class="no-data-message">
          <p>暂无考试记录数据</p>
        </div>
        
        <div class="chart-section">
            <div class="ai-chat-container">
              <div class="ai-chat-header">
                <h4>AI学情分析助手</h4>
              </div>
              <div class="ai-chat-messages" ref="chatMessages">
                <div v-if="aiMessages.length === 0" class="ai-welcome-message">
                  <p>欢迎使用AI学情分析助手！我可以帮助你分析该学生的考试成绩和学习情况。请输入你的问题，例如：</p>
                  <ul>
                    <li>分析这名学生的学习趋势</li>
                    <li>该学生的优势和不足是什么</li>
                    <li>如何提高该学生的学习成绩</li>
                  </ul>
                </div>
                <div v-for="(message, index) in aiMessages" :key="index" :class="['ai-message', message.type]">
                  <div class="ai-message-content">{{ message.content }}</div>
                  <div class="ai-message-time">{{ message.time }}</div>
                  <div v-if="message.type === 'ai' && !message.saved" class="ai-save-action">
                    <el-button type="primary" size="small" @click="saveAnalysisResult(message)">保存分析结果</el-button>
                  </div>
                  <div v-if="message.type === 'ai' && message.saved" class="ai-saved-tag">
                    <el-tag size="mini" type="success">已保存</el-tag>
                  </div>
                </div>
                <div v-if="isLoading" class="ai-loading">
                  <span>AI正在思考中</span>
                  <span class="dot-1">.</span>
                  <span class="dot-2">.</span>
                  <span class="dot-3">.</span>
                </div>
              </div>
              <!-- 添加快捷问题按钮区域 -->
              <div class="ai-quick-questions" v-if="aiMessages.length === 0 || aiMessages.length <= 2">
                <p class="quick-title">快捷问题：</p>
                <div class="quick-buttons">
                  <el-button 
                    size="small" 
                    round 
                    type="info" 
                    plain 
                    @click="fillPresetQuestion('分析这名学生的学习趋势')">
                    <i class="el-icon-data-analysis"></i> 学习趋势分析
                  </el-button>
                  <el-button 
                    size="small" 
                    round 
                    type="info" 
                    plain 
                    @click="fillPresetQuestion('该学生在' + teacherSubjectName + '学科上的优势和不足是什么')">
                    <i class="el-icon-s-opportunity"></i> 优势与不足
                  </el-button>
                  <el-button 
                    size="small" 
                    round 
                    type="info" 
                    plain 
                    @click="fillPresetQuestion('如何提高该学生的' + teacherSubjectName + '成绩')">
                    <i class="el-icon-s-promotion"></i> 成绩提升建议
                  </el-button>
                  <el-button 
                    size="small" 
                    round 
                    type="info" 
                    plain 
                    @click="fillPresetQuestion('如何针对该学生的学习特点进行个性化教学')">
                    <i class="el-icon-s-custom"></i> 个性化教学建议
                  </el-button>
                </div>
              </div>
              <div class="ai-chat-input">
                <el-input
                  v-model="aiInputMessage"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入您的问题，AI将分析学生学情..."
                  :disabled="isLoading"
                  @keyup.enter.native="handleAiSend"
                ></el-input>
                <el-button type="primary" :disabled="isLoading || !aiInputMessage.trim()" @click="handleAiSend">
                  <i class="el-icon-s-promotion"></i> 发送
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 添加自定义模态框 -->
  <div v-if="addExamDialogVisible" class="custom-modal-overlay" @click.self="handleCloseDialog">
    <div class="custom-modal-container">
      <div class="custom-modal-header">
        <h3>添加考试记录</h3>
        <span class="custom-modal-close" @click="handleCloseDialog">×</span>
      </div>
    <div class="exam-dialog-content">
        <el-form :model="examForm" :rules="examFormRules" ref="examFormRef" label-width="100px" class="exam-form">
          <el-form-item label="考试名称" prop="examName">
            <el-select
              v-model="examForm.examName"
              filterable
              allow-create
              default-first-option
              placeholder="输入或选择考试名称"
              style="width: 100%"
              popper-append-to-body
              @change="handleExamNameChange"
            >
              <el-option
                v-for="item in historyExamNames"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <div v-if="examNameInputError" class="exam-name-error">
              请输入考试名称
            </div>
        </el-form-item>
          <el-form-item label="考试时间" prop="examTime">
            <el-input
            v-model="examForm.examTime"
              placeholder="输入日期，格式：YYYY-MM-DD"
              style="width: 100%"
            >
              <template slot="append">
                <el-button @click="setDateToToday">今天</el-button>
              </template>
            </el-input>
            <div class="date-format-hint">日期格式示例: 2023-10-15</div>
        </el-form-item>
          <el-form-item :label="teacherSubjectName + '成绩'" prop="score">
              <el-input-number 
              v-model="examForm.score" 
                :min="0" 
                :max="100" 
                :precision="1" 
                :step="0.5" 
              placeholder="请输入成绩"
              style="width: 100%"
              controls-position="right"
              ></el-input-number>
          </el-form-item>
          <el-form-item :label="teacherSubjectName + '备注'" prop="remarks">
            <el-input
              v-model="examForm.remarks"
              type="textarea"
              :rows="2"
              :placeholder="'可选：添加关于' + teacherSubjectName + '考试的备注'"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="selected-date-debug" v-if="examForm.examTime">
          <p>已填写日期: {{ examForm.examTime }}</p>
      </div>
        <div v-if="suggestedExamNames.length > 0" class="suggested-names">
          <p class="suggested-title">推荐考试名称：</p>
          <el-tag
            v-for="name in suggestedExamNames"
            :key="name"
            size="small"
            @click="selectSuggestedExam(name)"
            class="suggested-tag"
          >{{ name }}</el-tag>
    </div>
      </div>
      <div class="custom-modal-footer">
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="submitSingleStudentExam" :loading="submitting">提交</el-button>
      </div>
    </div>
  </div>
  
  <!-- 修改考试记录模态框也采用同样方式 -->
  <div v-if="editExamDialogVisible" class="custom-modal-overlay" @click.self="handleCloseEditDialog">
    <div class="custom-modal-container">
      <div class="custom-modal-header">
        <h3>修改考试记录</h3>
        <span class="custom-modal-close" @click="handleCloseEditDialog">×</span>
      </div>
    <div class="exam-dialog-content">
        <!-- 添加考试记录选择列表 -->
        <div class="exam-records-list">
          <h4>历次考试记录</h4>
          <el-table
            :data="filteredExamRecords"
            border
            style="width: 100%; margin-bottom: 15px;"
            height="200"
            :header-cell-style="{background: '#f5f7fa', color: '#1b4380', fontWeight: 'bold'}"
            @current-change="handleEditExamRecordChange"
          >
            <el-table-column prop="examName" label="考试名称" width="180"></el-table-column>
            <el-table-column prop="examTime" label="考试时间" width="120" :formatter="formatDate"></el-table-column>
            <el-table-column :prop="teacherSubject" :label="teacherSubjectName" width="100" :formatter="formatScore"></el-table-column>
            <el-table-column :prop="teacherSubject + '_remarks'" :label="teacherSubjectName + '备注'" width="150" show-overflow-tooltip></el-table-column>
          </el-table>
        </div>
        
        <el-form :model="examForm" :rules="examFormRules" ref="editExamFormRef" label-width="100px" class="exam-form">
        <el-form-item label="考试名称">
          <span>{{ examForm.examName }}</span>
        </el-form-item>
          <el-form-item label="考试时间" prop="examTime">
            <el-input
              v-model="examForm.examTime"
              placeholder="输入日期，格式：YYYY-MM-DD"
              style="width: 100%"
            >
              <template slot="append">
                <el-button @click="setDateToToday">今天</el-button>
              </template>
            </el-input>
            <div class="date-format-hint">日期格式示例: 2023-10-15</div>
        </el-form-item>
          <el-form-item :label="teacherSubjectName" prop="score">
          <el-input-number 
            v-model="examForm.score" 
            :min="0" 
            :max="100" 
            :precision="1" 
            :step="0.5"
              style="width: 100%"
              controls-position="right"
          ></el-input-number>
        </el-form-item>
          <el-form-item :label="teacherSubjectName + '备注'" prop="remarks">
            <el-input
              v-model="examForm.remarks"
              type="textarea"
              :rows="2"
              :placeholder="'可选：添加关于' + teacherSubjectName + '考试的备注'"
            ></el-input>
        </el-form-item>
      </el-form>
        <div class="selected-date-debug" v-if="examForm.examTime">
          <p>已填写日期: {{ examForm.examTime }}</p>
    </div>
      </div>
      <div class="custom-modal-footer">
        <el-button @click="handleCloseEditDialog">取消</el-button>
        <el-button type="danger" @click="confirmDeleteExam" :disabled="!currentEditExam">删除记录</el-button>
        <el-button type="primary" @click="submitEditExam" :loading="submitting" :disabled="!currentEditExam">保存修改</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { fetchClassList, fetchStudentList, fetchStudentAnalysis, fetchExamRecords, aiAnalysis, saveAiAnalysis } from "@/api/aiStuAnalysis.js";
import axios from 'axios';

export default {
  name: "PerLearnCase",
  data() {
    // 日期格式验证函数
    const validateDate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入考试日期'));
      }
      
      // 检查日期格式是否符合YYYY-MM-DD
      const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
      if (!dateRegex.test(value)) {
        return callback(new Error('日期格式不正确，应为 YYYY-MM-DD'));
      }
      
      // 检查日期是否有效
      const dateParts = value.split('-');
      const year = parseInt(dateParts[0], 10);
      const month = parseInt(dateParts[1], 10) - 1; // 月份从0开始
      const day = parseInt(dateParts[2], 10);
      
      const date = new Date(year, month, day);
      if (
        date.getFullYear() !== year ||
        date.getMonth() !== month ||
        date.getDate() !== day
      ) {
        return callback(new Error('无效的日期'));
      }
      
      // 检查日期是否在将来
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      if (date > today) {
        return callback(new Error('考试日期不能在未来'));
      }
      
      callback();
    };
      
    return {
      // 教师相关
      teacherId: localStorage.getItem('teacherId') || '',
      teacherName: localStorage.getItem('teacherName') || '',
      teacherSubjectCode: '', // 后端获取的教师学科代码
      routeTeacherSubject: '', // 从路由参数获取的教师学科代码
      
      // 学生相关
      studentId: '',
      studentName: '',
      studentClass: null, // 当前学生班级
      classId: null, // 当前选中的班级ID
      subject: null, // 当前选中的学科
      subjects: [], // 动态学科列表
      studentData: {}, // 学生学情数据
      chartType: "考试", // 当前图表类型
      selectedStudent: { id: null, name: "" }, // 当前选中学生
      classList: [], // 班级列表
      studentList: [], // 学生列表
      searchQuery: "", // 搜索关键字
      showFocusOnly: false, // 是否只显示关注的学生
      // 学生历次考试记录
      examRecords: [],
      // 新增变量
      selectedExam: null, // 当前选中的考试记录
      addExamDialogVisible: false, // 添加考试记录对话框
      editExamDialogVisible: false, // 修改考试记录对话框
      examForm: {
        examName: "",
        examTime: "",
        score: "",
        remarks: "" // 新增备注字段
      },
      classStudents: [], // 当前班级所有学生
      // 添加日期选择器配置
      datePickerOptions: {
        disabledDate(time) {
          // 禁用未来日期
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          },
          {
            text: '本月初',
            onClick(picker) {
              const date = new Date();
              date.setDate(1);
              picker.$emit('pick', date);
            }
          },
          {
            text: '上月初',
            onClick(picker) {
              const date = new Date();
              date.setMonth(date.getMonth() - 1);
              date.setDate(1);
              picker.$emit('pick', date);
            }
          }
        ]
      },
      // 添加表单验证规则
      examFormRules: {
        examName: [
          { required: true, message: '请输入考试名称', trigger: 'blur' },
          { min: 2, max: 30, message: '考试名称长度应在2到30个字符之间', trigger: 'blur' }
        ],
        examTime: [
          { required: true, message: '请输入考试时间', trigger: 'blur' },
          { validator: validateDate, trigger: 'blur' }
        ],
        score: [
          { required: true, message: '请输入考试成绩', trigger: 'blur' },
          { type: 'number', message: '成绩必须为数字', trigger: 'blur' }
        ]
      },
      historyExamNames: [], // 历史考试名称
      suggestedExamNames: [], // 推荐的考试名称
      submitting: false, // 提交状态
      // 添加教师信息相关数据
      teacherId: null, // 当前教师ID
      teacherName: null, // 当前教师姓名
      teacherSubjectCode: '', // 从后端获取的教师学科代码
      // 添加新属性
      examNameInputError: false,
      currentEditExam: null, // 当前正在编辑的考试记录
      aiMessages: [], // 存储AI回复的消息
      aiInputMessage: '', // 用户输入的问题
      isLoading: false, // 是否正在加载AI回复
      lastAnalysisResult: null, // 最后一次AI分析结果
    };
  },
  computed: {
    filteredStudents() {
      let students = this.studentList;
      if (this.showFocusOnly) {
        students = students.filter((student) => student.focus);
      }
      if (this.searchQuery) {
        students = students.filter((student) =>
          student.name.includes(this.searchQuery)
        );
      }
      return students;
    },
    
    // 修改教师学科计算属性，使用后端数据而非硬编码
    teacherSubject() {
      // 打印每次计算属性被调用时的状态
      console.log("[teacherSubject计算属性] 调用时状态:", {
        routeTeacherSubject: this.routeTeacherSubject,
        teacherSubjectCode: this.teacherSubjectCode,
        localStorageSubject: localStorage.getItem('teacherSubject')
      });
      
      // 优先使用从路由参数获取的教师学科
      if (this.routeTeacherSubject) {
        console.log("[teacherSubject计算属性] 使用路由参数:", this.routeTeacherSubject);
        return this.routeTeacherSubject;
      }
      
      // 其次使用从后端获取的教师学科代码
      if (this.teacherSubjectCode) {
        console.log("[teacherSubject计算属性] 使用后端获取的学科代码:", this.teacherSubjectCode);
        return this.teacherSubjectCode;
      }
      
      // 尝试从localStorage获取
      const storedSubject = localStorage.getItem('teacherSubject');
      if (storedSubject) {
        console.log("[teacherSubject计算属性] 使用localStorage中的学科:", storedSubject);
        return storedSubject;
      }
      
      // 从localStorage获取teacherId
      const teacherId = localStorage.getItem('teacherId');
      if (teacherId) {
        // 如果有teacherId但还没获取学科，触发获取
        console.log("[teacherSubject计算属性] 有teacherId但没有学科，触发获取:", teacherId);
        this.fetchTeacherInfo(teacherId);
      } else {
        console.log("[teacherSubject计算属性] 没有找到teacherId，无法自动获取学科");
      }
      
      // 返回空字符串而不是默认值
      console.log("[teacherSubject计算属性] 没有找到学科信息，返回空字符串");
      return '';
    },
    
    // 获取当前教师学科名称
    teacherSubjectName() {
      const subjectMap = {
        'chinese': '语文',
        'math': '数学',
        'english': '英语',
        'physics': '物理',
        'chemistry': '化学',
        'politics': '政治',
        'history': '历史',
        'geography': '地理',
        'biology': '生物'
      };
      
      const displayName = subjectMap[this.teacherSubject] || '全科';
      console.log("[teacherSubjectName计算属性] 当前学科代码:", this.teacherSubject, "显示名称:", displayName);
      return displayName;
    },
    // 添加新的计算属性，过滤当前教师学科的考试记录
    filteredExamRecords() {
      if (!this.examRecords || !this.teacherSubject) return [];
      const filtered = this.examRecords.filter(record => 
        record[this.teacherSubject] !== null && 
        record[this.teacherSubject] !== undefined
      );
      
      // 当过滤结果发生变化且存在记录，且当前没有选中记录时，自动选中第一条
      if (filtered.length > 0 && this.editExamDialogVisible && !this.currentEditExam) {
        this.$nextTick(() => {
          this.handleEditExamRecordChange(filtered[0]);
        });
      }
      
      return filtered;
    },
  },
  mounted() {
    this.initializeData(); // 初始化数据
    this.studentId = this.$route.params.studentId; // 获取路由参数
    
    // 如果路由参数中有学生姓名，则设置它
    if (this.$route.params.studentName) {
      this.studentName = this.$route.params.studentName;
    }
    
    // 获取路由参数中的教师学科
    if (this.$route.params.teacherSubject) {
      this.routeTeacherSubject = this.$route.params.teacherSubject;
      console.log("从路由参数获取到教师学科:", this.routeTeacherSubject);
      // 保存到localStorage，以便于后续使用
      localStorage.setItem('teacherSubject', this.routeTeacherSubject);
    }
    
    // 尝试从localStorage获取更多信息
    if (this.studentId) {
      // 获取学生信息
      this.fetchStudentInfo();
      // 获取学生考试记录
      this.fetchExamRecords(this.studentId);
    }
    
    // 初始化时获取教师信息
    this.initTeacherInfo();
  },
  methods: {
    // 格式化日期
    formatDate(row, column) {
      if (!row[column.property]) return '';
      const date = new Date(row[column.property]);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    
    // 格式化成绩，保留一位小数
    formatScore(row, column) {
      const score = row[column.property];
      if (score === null || score === undefined || isNaN(score)) {
        return '0.0';
      }
      return Number(score).toFixed(1);
    },
    
    // 处理考试行选择变更
    handleExamRowChange(row) {
      console.log("选择了考试记录:", row);
      this.selectedExam = row;
    },
    
    // 处理关闭对话框
    handleCloseDialog(done) {
      // 如果正在提交，则不关闭对话框
      if (this.submitting) {
        this.$message.warning("正在提交，请稍候...");
        return;
      }
      
      // 重置表单
      if (this.$refs.examFormRef) {
        this.$refs.examFormRef.resetFields();
      }
      
      this.addExamDialogVisible = false;
      // 重置错误状态
      this.examNameInputError = false;
      if (done) done();
    },
    
    // 处理关闭编辑对话框
    handleCloseEditDialog(done) {
      // 如果正在提交，则不关闭对话框
      if (this.submitting) {
        this.$message.warning("正在提交，请稍候...");
        return;
      }
        
      // 重置表单
      if (this.$refs.editExamFormRef) {
        this.$refs.editExamFormRef.resetFields();
      }
      
      this.editExamDialogVisible = false;
      this.currentEditExam = null; // 重置当前编辑的考试记录
      // 移除对done的调用，因为它不是函数
    },
    
    // 添加设置日期为今天的方法
    setDateToToday() {
      this.examForm.examTime = this.formatDateToString(new Date());
      console.log("设置日期为今天:", this.examForm.examTime);
    },
    
    // 显示添加考试记录对话框
    showAddExamDialog() {
      console.log("点击添加考试记录按钮");
      
      // 验证当前是否有学生选中
      if (!this.studentId) {
        this.$message.warning("请先选择一名学生");
            return;
          }
          
      // 加载历史考试名称
      this.loadHistoryExamNames();
      
      // 生成推荐考试名称
      this.generateSuggestedExamNames();
      
      // 获取当前日期格式化字符串
      const currentDate = this.formatDateToString(new Date());
      console.log("当前日期:", currentDate);
      
      // 初始化表单，默认使用当前日期
      this.examForm = {
        examName: "",
        examTime: currentDate, // 使用当前日期
        score: "", // 当前教师学科的成绩
        remarks: "" // 初始化备注为空
      };
      
      // 重置错误状态
      this.examNameInputError = false;
      
      console.log("初始化表单:", this.examForm);
      console.log("打开添加考试记录对话框，当前学生ID:", this.studentId);
      
      // 使用Vue.nextTick确保在DOM更新后再设置对话框状态
      this.$nextTick(() => {
        this.addExamDialogVisible = true;
        console.log("对话框可见状态:", this.addExamDialogVisible);
        
        // 强制更新
        this.$forceUpdate();
      });
    },
    
    // 显示修改考试记录对话框，修改为显示所有考试记录
    showEditExamDialog() {
      if (!this.selectedExam) {
        this.$message.warning("请先选择一条考试记录");
        return;
      }
      
      // 初始设置当前编辑的考试记录
      this.currentEditExam = this.selectedExam;
      
      // 获取当前考试记录的日期，确保格式正确
      let examTime = this.selectedExam.examTime;
      
      // 如果日期不是YYYY-MM-DD格式，尝试格式化它
      if (examTime && typeof examTime === 'string' && !examTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
        try {
          const dateObj = new Date(examTime);
          if (!isNaN(dateObj.getTime())) {
            examTime = this.formatDateToString(dateObj);
          }
        } catch (e) {
          console.error("日期格式化错误:", e);
        }
      }
      
      // 填充表单
      this.examForm = {
        examName: this.selectedExam.examName,
        examTime: examTime,
        score: this.selectedExam[this.teacherSubject], // 获取当前教师学科的成绩
        remarks: this.selectedExam[`${this.teacherSubject}_remarks`] || "" // 获取特定学科的备注
      };
      
      console.log("修改考试记录表单:", this.examForm);
      
      this.editExamDialogVisible = true;
      
      // 使用Vue.nextTick确保在DOM更新后再设置对话框状态
      this.$nextTick(() => {
        // 如果有考试记录但没有选中，则选择第一条
        if (this.filteredExamRecords.length > 0 && !this.currentEditExam) {
          this.handleEditExamRecordChange(this.filteredExamRecords[0]);
        }
        
        // 强制更新
        this.$forceUpdate();
      });
    },
    
    // 确认删除考试记录，修改为使用currentEditExam
    confirmDeleteExam() {
      if (!this.currentEditExam) {
        this.$message.warning("请先选择一条考试记录");
        return;
      }
      this.$confirm(`确定要删除考试 "${this.currentEditExam.examName}" 的记录吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.deleteExamRecord();
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    
    // 删除考试记录，修改为使用currentEditExam
    async deleteExamRecord() {
      try {
        // 准备要删除的数据
        const deleteData = {
          examId: this.currentEditExam.id,
          studentId: this.studentId
        };
        
        console.log("准备删除考试记录:", deleteData);
        
        // 获取认证令牌
        const token = this.getAuthToken();
        
        // 调用删除API，包含认证头
        const response = await axios.delete("/api/teaching/exam-records/delete", {
          data: deleteData,
          headers: {
            'Authorization': token ? `Bearer ${token}` : '',
            'Content-Type': 'application/json'
          }
        });
        
        console.log("删除考试记录响应:", response);
        
        if (response && response.data && response.data.status === "success") {
          // 使用对话框代替简单消息
          this.$confirm('考试记录删除成功！', '操作成功', {
            confirmButtonText: '确定',
            type: 'success',
            showCancelButton: false,
            center: true
          }).then(() => {
            // 关闭编辑对话框
            this.handleCloseEditDialog();
            
          // 重新加载考试记录
          this.fetchExamRecords(this.studentId);
          this.selectedExam = null;
            this.currentEditExam = null;
          });
        } else {
          console.warn("删除考试记录API返回异常:", response);
          this.$message.error(response?.data?.message || "删除考试记录失败，请稍后重试");
        }
      } catch (error) {
        console.error("删除考试记录失败:", error);
        if (error.response && error.response.status === 401) {
          this.$message.error("身份验证失败，请重新登录");
          // 可以在这里添加重定向到登录页面的逻辑
        } else {
        this.$message.error("删除考试记录失败: " + (error.message || "未知错误"));
        }
      }
    },
    
    // 加载历史考试名称
    loadHistoryExamNames() {
      const examNames = new Set();
      if (this.examRecords && this.examRecords.length > 0) {
        this.examRecords.forEach(record => {
          if (record.examName) {
            examNames.add(record.examName);
          }
        });
      }
      this.historyExamNames = Array.from(examNames);
      console.log("已加载历史考试名称:", this.historyExamNames);
    },
    
    // 生成推荐考试名称
    generateSuggestedExamNames() {
      const today = new Date();
      const currentMonth = today.getMonth() + 1;
      const currentYear = today.getFullYear();
      
      // 根据当前日期生成常见考试名称
      const suggestions = [
        `${currentYear}年${currentMonth}月月考`,
        `${currentYear}年第${Math.ceil(currentMonth / 3)}季度考试`,
        `${currentYear}年期中考试`,
        `${currentYear}年期末考试`,
        `${currentYear}学年第${currentMonth > 7 ? 1 : 2}学期考试`
      ];
      
      this.suggestedExamNames = suggestions;
      console.log("已生成推荐考试名称:", this.suggestedExamNames);
    },
    
    // 选择推荐的考试名称
    selectSuggestedExam(name) {
      this.examForm.examName = name;
      this.examNameInputError = false;
    },
    
    // 获取用户令牌
    getAuthToken() {
      return localStorage.getItem('token') || 
             localStorage.getItem('accessToken') || 
             localStorage.getItem('authToken') || 
             localStorage.getItem('jwtToken');
    },
    
    // 处理考试名称变更
    handleExamNameChange(value) {
      console.log("考试名称变更:", value);
      this.examForm.examName = value;
      this.examNameInputError = !value;
    },
    
    // 修改生成唯一ID的函数 - 不再使用此函数
    generateUniqueId() {
      // 保留此方法但不再使用，只返回null
      console.log("警告：不再生成ID，依赖数据库自增功能");
      return null;
    },
    
    // 提交添加考试记录
    async submitSingleStudentExam() {
      if (!this.examForm.examName) {
        this.$message.warning("请输入考试名称");
        return;
      }
      
      if (!this.studentId) {
        this.$message.warning("请选择学生");
        return;
      }
      
      this.$refs.examFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error("请检查表单信息");
        return;
      }
      
        this.submitting = true;
        
        // 定义变量放在try块外部以便在catch块中也可以访问
        let apiUrl = '';
        let method = '';
        let requestData = {};
        
        try {
          // 先重新获取最新的考试记录
          try {
            await this.fetchExamRecords(this.studentId);
            console.log("重新获取考试记录完成，检查是否存在重复记录");
          } catch (fetchError) {
            console.error("重新获取考试记录失败:", fetchError);
            // 继续执行，即使获取失败也尝试提交
          }
          
          // 检查是否存在具有相同考试名称的记录 - 增强匹配逻辑
          const normalizedExamName = this.examForm.examName.trim().toLowerCase();
          const existingExam = this.examRecords.find(record => {
            // 获取考试名称，处理可能的字段名差异
            const recordExamName = (record.examName || record.exam_name || '').trim().toLowerCase();
            // 同时匹配学生ID和考试名称
            return recordExamName === normalizedExamName && 
                   (record.student_id === this.studentId || record.studentId === this.studentId);
          });
          
          // 获取当前教师学科
          const subject = this.teacherSubject;
          
          if (existingExam) {
            console.log("找到已存在的考试记录，将执行更新操作:", existingExam);
            apiUrl = '/api/teaching/exam-records/update';
            method = 'put';
            
            // 构建更新请求 - 只更新当前学科成绩
            requestData = {
              examId: existingExam.id,
              studentId: this.studentId,
              [subject]: parseFloat(this.examForm.score) || 0,
              [`${subject}_remarks`]: this.examForm.remarks || ''
            };
          } else {
            console.log("未找到已存在的考试记录，将创建新记录");
            apiUrl = '/api/teaching/exam-records/add';
            method = 'post';
            
            // 构建请求数据 - 不要提供id字段
            requestData = {
              examName: this.examForm.examName.trim(),
              // 使用examTime与后端期望一致
              examTime: this.examForm.examTime,
              students: [{
                studentId: this.studentId,
                [subject]: parseFloat(this.examForm.score) || 0,
                [`${subject}_remarks`]: this.examForm.remarks || ''
              }]
            };
            
            // 记录请求格式
            console.log("添加考试记录的请求格式:", JSON.stringify(requestData, null, 2));
          }
          
          console.log(`准备${existingExam ? '更新' : '添加'}考试记录:`, requestData);
          
          // 获取认证令牌
          const token = this.getAuthToken();
          
          // 添加调试日志，记录发送前的请求数据
          console.log("发送请求前的完整数据:", JSON.stringify(requestData, null, 2));
          console.log("检查examTime字段是否存在:", requestData.examTime);
          
          // 发送请求
          const response = await axios({
            method: method,
            url: apiUrl,
            data: requestData,
            headers: {
              'Authorization': token ? `Bearer ${token}` : '',
              'Content-Type': 'application/json'
            }
          });
          
          console.log(`${existingExam ? '更新' : '添加'}考试记录响应:`, response);
        
        if (response && response.data && response.data.status === "success") {
            // 操作成功
            const actionType = existingExam ? '更新' : '添加';
            // 使用更醒目的对话框而不是简单消息
            this.$confirm(`${this.getSubjectName(subject)}成绩${actionType}成功！`, '操作成功', {
                confirmButtonText: '确定',
                type: 'success',
                showCancelButton: false,
                center: true
            }).then(() => {
                this.handleCloseDialog();
          this.fetchExamRecords(this.studentId);
            });
            
            // 更新历史考试名称
            if (!this.historyExamNames.includes(this.examForm.examName)) {
                this.historyExamNames.push(this.examForm.examName);
            }
        } else {
            console.warn(`考试记录${existingExam ? '更新' : '添加'}失败:`, response);
            this.$message.error(response?.data?.message || `考试记录${existingExam ? '更新' : '添加'}失败，请稍后重试`);
        }
      } catch (error) {
          console.error("操作考试记录失败:", error);
          
          // 详细记录错误信息
          console.error("详细错误信息:", {
            message: error.message,
            responseStatus: error.response?.status,
            responseData: error.response?.data,
            requestData: requestData || "未定义",
            apiUrl: apiUrl || "未定义"
          });
          
          // 错误处理
          if (error.response) {
            if (error.response.data) {
              const errorMessage = error.response.data.message || '';
              
              // 检查是否为数据截断错误（id超出范围）
              if (error.response.status === 500 && 
                  errorMessage.includes("Data truncation") && 
                  errorMessage.includes("Out of range value for column 'id'")) {
                console.error("数据库ID范围错误:", errorMessage);
                this.$message({
                  type: 'error',
                  dangerouslyUseHTMLString: true,
                  message: `<div>
                    <p><strong>添加考试记录失败：数据库ID超出范围</strong></p>
                    <p>系统数据库ID已达到最大值，请联系系统管理员处理。</p>
                  </div>`,
                  duration: 10000,
                  showClose: true
                });
                return;
              }
              
              // 处理新的重复记录错误 - 触发器返回的自定义错误
              if (error.response.status === 500 && 
                  (errorMessage.includes('DUPLICATE_RECORD_FOUND'))) {
                console.log("检测到DUPLICATE_RECORD_FOUND错误，尝试自动更新现有记录");
                
                try {
                    // 重新获取学生的考试记录
                    const records = await this.fetchExamRecordsData(this.studentId);
                    
                    // 查找匹配的记录（匹配学生ID和考试名称）
                    const duplicateRecord = records.find(record => 
                        record.student_id === this.studentId && 
                        record.exam_name === this.examForm.examName.trim());
                    
                    if (duplicateRecord) {
                        console.log("找到需要更新的记录:", duplicateRecord);
                        
                        // 获取教师学科
                        const subject = this.teacherSubject;
                        
                        // 构建更新请求 - 只更新当前学科成绩
                        const updateData = {
                            examId: duplicateRecord.id,
                            studentId: this.studentId,
                            [subject]: parseFloat(this.examForm.score) || 0,
                            [`${subject}_remarks`]: this.examForm.remarks || ''
                        };
                        
                        console.log("自动执行记录更新，更新数据:", updateData);
                        
                        // 发送更新请求
                        const response = await axios({
                            method: 'put',
                            url: '/api/teaching/exam-records/update',
                            data: updateData,
                            headers: {
                                'Authorization': this.getAuthToken() ? `Bearer ${this.getAuthToken()}` : '',
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        if (response && response.data && response.data.status === "success") {
                            // 使用对话框代替简单消息，显示更醒目
                            this.$confirm(`检测到记录已存在，已自动更新${this.getSubjectName(subject)}成绩`, '更新成功', {
                                confirmButtonText: '确定',
                                type: 'success',
                                showCancelButton: false,
                                center: true
                            }).then(() => {
                                this.handleCloseDialog();
                                this.fetchExamRecords(this.studentId);
                            });
                        } else {
                            this.$message.error("更新考试记录失败: " + (response?.data?.message || '未知错误'));
                        }
                    } else {
                        this.$message.error("无法找到要更新的考试记录，请刷新页面后重试");
                    }
                } catch (updateError) {
                    console.error("自动更新考试记录时出错:", updateError);
                    this.$message.error("更新考试记录失败: " + (updateError.response?.data?.message || updateError.message));
                }
                return;
            }
            
            // 处理唯一约束冲突错误 - 自动执行更新操作
            if (error.response.status === 500 && 
                (errorMessage.includes('Duplicate entry') || 
                 errorMessage.includes('unique_student_exam'))) {
              
              console.log("检测到唯一约束冲突，自动执行更新操作");
              
              // 直接执行更新操作，无需用户确认
              try {
                // 重新获取考试记录以确保数据最新
                await this.fetchExamRecords(this.studentId);
                
                // 找到要更新的记录
                const duplicateRecord = this.examRecords.find(record => {
                  const recordExamName = (record.examName || record.exam_name || '').trim().toLowerCase();
                  const newExamName = this.examForm.examName.trim().toLowerCase();
                  return (record.student_id === this.studentId || record.studentId === this.studentId) 
                         && recordExamName === newExamName;
                });
                
                if (duplicateRecord) {
                  console.log("找到需要更新的记录:", duplicateRecord);
                  
                  // 获取教师学科
                  const subject = this.teacherSubject;
                  
                  // 构建更新请求 - 只更新当前学科成绩
                  const updateData = {
                    examId: duplicateRecord.id,
                    studentId: this.studentId,
                    [subject]: parseFloat(this.examForm.score) || 0,
                    [`${subject}_remarks`]: this.examForm.remarks || ''
                  };
                  
                  console.log("自动执行记录更新，更新数据:", updateData);
                  
                  // 发送更新请求
                  const response = await axios({
                    method: 'put',
                    url: '/api/teaching/exam-records/update',
                    data: updateData,
                    headers: {
                      'Authorization': this.getAuthToken() ? `Bearer ${this.getAuthToken()}` : '',
                      'Content-Type': 'application/json'
                    }
                  });
                  
                  if (response && response.data && response.data.status === "success") {
                    this.$message.success(`检测到记录已存在，已自动更新${this.getSubjectName(subject)}成绩`);
                    this.handleCloseDialog();
                    this.fetchExamRecords(this.studentId);
                  } else {
                    this.$message.error("更新考试记录失败: " + (response?.data?.message || '未知错误'));
                  }
                } else {
                  this.$message.error("无法找到要更新的考试记录，请刷新页面后重试");
                }
              } catch (updateError) {
                console.error("自动更新考试记录时出错:", updateError);
                this.$message.error("更新考试记录失败: " + (updateError.response?.data?.message || updateError.message));
              }
              return;
            }
            
            // 其他错误处理
            this.$message.error("操作考试记录失败: " + errorMessage);
          } else {
            this.$message.error(`操作失败 (${error.response.status})`);
          }
        } else {
          this.$message.error("网络错误，请检查网络连接");
        }
      } finally {
        // 确保无论如何都重置提交状态
        this.submitting = false;
      }
      });
    },
    
    // 获取科目名称的方法
    getSubjectName(subjectCode) {
      const subjectMap = {
        'chinese': '语文',
        'math': '数学',
        'english': '英语',
        'physics': '物理',
        'chemistry': '化学',
        'biology': '生物',
        'politics': '政治',
        'history': '历史',
        'geography': '地理'
      };
      return subjectMap[subjectCode] || subjectCode;
    },
    
    // 修改submitEditExam方法，适配数据库变更
    async submitEditExam() {
      // 表单验证
      this.$refs.editExamFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.warning("请完善表单信息");
        return;
      }
      
        // 确保有学生ID和考试ID
        if (!this.studentId || !this.currentEditExam?.id) {
          this.$message.warning("无法确定要修改的考试记录，请重新选择");
          return;
        }
        
        // 获取教师学科
        const subject = this.teacherSubject;
        if (!subject) {
          this.$message.warning("无法确定教师学科，请确认登录信息");
          return;
        }
        
        // 设置提交状态
        this.submitting = true;
        
        try {
      // 准备要更新的数据
      const updateData = {
            examId: parseInt(this.currentEditExam.id), // 确保是整数
        studentId: this.studentId,
            examTime: this.examForm.examTime,
            // 只更新当前教师学科的成绩
            [subject]: parseFloat(this.examForm.score) || 0,
            // 更新备注
            [`${subject}_remarks`]: this.examForm.remarks || ''
      };
      
      console.log("准备更新考试记录:", updateData);
      
          // 获取认证令牌
          const token = this.getAuthToken();
          
          // 执行更新
          const response = await axios.put("/api/teaching/exam-records/update", updateData, {
            headers: {
              'Authorization': this.getAuthToken() ? `Bearer ${this.getAuthToken()}` : '',
              'Content-Type': 'application/json'
            }
          });
          
          console.log("更新考试记录响应:", response);
        
        if (response && response.data && response.data.status === "success") {
            // 使用对话框代替简单消息
            this.$confirm('考试记录更新成功！', '操作成功', {
              confirmButtonText: '确定',
              type: 'success',
              showCancelButton: false,
              center: true
            }).then(() => {
              // 关闭编辑对话框
              this.handleCloseEditDialog();
              
              // 重新获取考试记录，确保显示最新数据
          this.fetchExamRecords(this.studentId);
            });
        } else {
            console.warn("更新考试记录API返回异常:", response);
            this.$message.error(response?.data?.message || "更新考试记录失败，请稍后重试");
        }
      } catch (error) {
          console.error("更新考试记录失败:", error);
          // 显示详细错误信息以便调试
          if (error.response) {
            console.error("错误响应:", error.response);
            if (error.response.data) {
              console.error("错误详情:", error.response.data);
              // 如果后端返回了具体错误消息，显示给用户
              this.$message.error("更新考试记录失败: " + (error.response.data.message || error.message || "服务器内部错误"));
            } else {
              this.$message.error("更新考试记录失败: " + error.message);
            }
          } else {
            this.$message.error("更新考试记录失败: " + (error.message || "未知错误"));
          }
        } finally {
          // 重置提交状态
          this.submitting = false;
        }
      });
    },
    
    async initializeData() {
      try {
        console.log("开始初始化数据");
        
        // 获取从 Analysis 页面传递的选中学生数据
        const selectedStudents = this.$route.params.students || [];
        if (selectedStudents.length > 0) {
          const student = selectedStudents[0];
          this.studentId = student.id;
          this.studentName = student.name;
          this.studentClass = student.className || '未知班级';
          
          this.selectedStudent = {
            value: student.id,
            label: student.name,
          };
          
          this.fetchStudentData(); // 加载选中学生的学情数据
          this.fetchExamRecords(student.id); // 获取学生考试记录
        }

        // 加载班级和学生数据
        await this.fetchClassAndStudentData();
        
        // 如果路由参数中有studentId但没有其他学生信息，尝试获取完整学生信息
        if (this.studentId && (!this.studentName || !this.studentClass)) {
          await this.fetchStudentInfo();
        }
        
        console.log("初始化数据完成", {
          studentId: this.studentId,
          studentName: this.studentName,
          studentClass: this.studentClass
        });
      } catch (error) {
        console.error("初始化数据失败:", error);
        this.$message.error("初始化数据失败，请刷新页面重试");
      }
    },
    async fetchClassAndStudentData() {
      try {
        console.log("开始获取班级和学生数据");
        // 获取班级列表
        const classResponse = await fetchClassList();
        console.log("班级列表响应:", classResponse);
        
        // 检查响应数据结构
        if (!classResponse || !classResponse.data) {
          console.warn("班级列表API返回的数据结构不符合预期:", classResponse);
          this.$message.warning("无法获取班级列表数据");
          this.classList = [];
          this.classOptions = [];
          return;
        }
        
        // 格式化班级列表数据
        this.classList = Array.isArray(classResponse.data) ? classResponse.data : [];
        console.log("班级列表数据:", this.classList);
        
        if (this.classList.length === 0) {
          console.warn("班级列表为空");
          this.classOptions = [];
          return;
        }

        // 获取每个班级的学生列表
        const classOptions = await Promise.all(
          this.classList.map(async (cls) => {
            try {
              console.log(`获取班级ID为${cls.id}的学生列表`);
              const studentResponse = await fetchStudentList(cls.id, 1, 100);
              console.log(`班级${cls.id}学生列表响应:`, studentResponse);
              
              // 检查学生数据结构
              if (!studentResponse || !studentResponse.data) {
                console.warn(`班级${cls.id}学生列表返回数据结构不符合预期:`, studentResponse);
                return {
                  value: cls.id,
                  label: cls.name || cls.className || `班级${cls.id}`,
                  children: []
                };
              }
              
              // 检查students字段，注意这里后端可能返回data.data或data.students
              const students = studentResponse.data.data || studentResponse.data.students || [];
              console.log(`班级${cls.id}学生列表数据:`, students);

              return {
                value: cls.id,
                label: cls.name || cls.className || `班级${cls.id}`,
                children: Array.isArray(students) ? students.map((stu) => ({
                  value: stu.id || stu.studentId,
                  label: stu.name || `学生${stu.id || stu.studentId}`
                })) : []
              };
            } catch (err) {
              console.error(`获取班级${cls.id}学生列表失败:`, err);
              return {
                value: cls.id,
                label: cls.name || cls.className || `班级${cls.id}`,
                children: []
              };
            }
          })
        );

        console.log("最终生成的班级选项:", classOptions);
        this.classOptions = classOptions;
      } catch (error) {
        console.error("获取班级和学生数据失败:", error);
        this.$message.error("获取班级和学生数据失败，请稍后重试");
        this.classList = [];
        this.classOptions = [];
      }
    },
    handleStudentChange(value) {
      console.log("选中的学生:", value);
      if (value && value.length > 0) {
        // 获取学生ID - 级联选择器中最后一个值是学生ID
        const studentId = value[value.length - 1];
        // 确保studentId是一个有效值
        if (!studentId) {
          console.warn("选中的学生ID无效:", value);
          return;
        }
        
        this.studentId = studentId;
        // 确保studentId是一个字符串
        const studentIdStr = String(studentId);
        console.log(`学生ID格式化为字符串: ${studentIdStr}`);
        
        // 设置选中学生的显示名
        const classOptions = this.classOptions || [];
        let studentName = "未知学生";
        let className = "未知班级";
        
        // 尝试从级联选择器的选项中找到学生名称和班级
        for (const classOption of classOptions) {
          if (classOption.value === value[0] && classOption.children) {
            className = classOption.label;
            const student = classOption.children.find(stu => stu.value === studentId);
            if (student) {
              studentName = student.label;
              break;
            }
          }
        }
        
        console.log(`选中学生: ${studentName}(ID:${studentIdStr}), 班级: ${className}`);
        
        // 更新变量
        this.studentName = studentName;
        this.studentClass = className;
        this.selectedStudent = {
          value: value,
          label: studentName
        };
        
        this.fetchStudentData(); // 加载选中学生的学情数据
        this.fetchExamRecords(studentIdStr); // 获取学生考试记录
      }
    },
    async fetchStudentList() {
      try {
        // 需要提供一个classId，否则API会报错
        // 如果没有指定classId，尝试使用第一个可用的班级ID
        if (!this.classId && this.classList && this.classList.length > 0) {
          this.classId = this.classList[0].id;
        }
        
        // 如果仍然没有classId，则给出警告并退出
        if (!this.classId) {
          console.warn("缺少班级ID，无法获取学生列表");
          this.$message.warning("请先选择班级");
          return;
        }
        
        const response = await fetchStudentList(this.classId, 1, 100); // 添加classId参数
        this.studentList = response.data.students || response.data.data || []; // 适应不同的响应格式
        console.log(`成功获取班级[${this.classId}]的学生列表:`, this.studentList);
      } catch (error) {
        console.error("获取学生列表失败:", error);
        this.$message.error("获取学生列表失败，请稍后重试");
      }
    },
    async fetchStudentData() {
      if (!this.studentId) return; // 如果没有学生ID，则不执行后续操作
      
      try {
        // 使用教师的学科
        const subject = this.teacherSubject || 'all';
        
        // 调用 API 获取学生学情数据
        const response = await fetchStudentAnalysis(this.studentId, subject);
        this.studentData = response.data || {}; 
        this.loadChart(); // 加载图表
      } catch (error) {
        console.error("获取学生学情数据失败:", error);
      }
    },
    // 获取学生历次考试记录
    async fetchExamRecords(studentId) {
      if (!studentId) {
        console.warn("未提供学生ID，无法获取考试记录");
        this.examRecords = [];
        return;
      }
      
      try {
        console.log(`开始请求学生ID为${studentId}的考试记录数据`);
        console.log("当前教师学科:", this.teacherSubject);
        console.log("当前teacherSubjectCode:", this.teacherSubjectCode);
        
        // 获取认证令牌
        const token = this.getAuthToken();
        
        // 使用认证头从后端获取真实数据
        const response = await fetchExamRecords(studentId, token);
        console.log("考试记录API响应:", response);
        
        if (!response || !response.data) {
          console.warn("考试记录API返回数据结构不符合预期:", response);
          this.examRecords = [];
          return;
        }
        
        if (response.data.status === "success") {
          let records = response.data.data || [];
          
          // 筛选出对应科目不为空的记录
          const subject = this.teacherSubject;
          if (subject) {
            records = records.filter(record => {
              return record[subject] !== null && 
                     record[subject] !== undefined && 
                     record[subject] !== '';
            });
          }
          
          this.examRecords = records;
          console.log(`成功获取到${records.length}条考试记录，过滤后显示非空数据`);
          
          // 如果有考试记录，默认选中第一条
          if (records.length > 0) {
            this.selectedExam = records[0];
            console.log("自动选中第一条考试记录:", this.selectedExam);
          }
        } else {
          console.warn(`考试记录API返回状态不是success: ${response.data.status}`);
          this.examRecords = [];
          this.$message.warning(response.data.message || "未能获取考试记录");
        }
      } catch (error) {
        console.error("获取学生考试记录失败:", error);
        if (error.response && error.response.status === 401) {
          this.$message.error("身份验证失败，请重新登录");
          // 可以在这里添加重定向到登录页面的逻辑
        } else {
        this.$message.error("获取学生考试记录失败，请稍后重试");
        }
        this.examRecords = [];
      }
    },
    selectStudent(student) {
      this.selectedStudent = student; // 更新选中学生
      this.subject = null; // 重置学科选择
      this.studentId = student.id;
      this.studentName = student.name;
      this.studentClass = student.className || "未知班级";
      
      this.fetchStudentData(); // 切换学生时重新加载学情数据
      this.fetchExamRecords(student.id); // 获取学生考试记录
      console.log("选中学生:", student);
    },
    searchStudent() {
      console.log("搜索学生:", this.searchQuery);
    },

    loadChart() {
      // 确保有学生ID
      if (!this.studentId) {
        console.warn("未选择学生，无法加载图表");
        return;
      }
      
      // 确保有学科
      const subject = this.teacherSubject;
      if (!subject) {
        console.warn("无法确定教师学科，不能加载图表");
        return;
      }
      
      console.log(`准备加载${this.studentName}的${this.chartType}图表数据，学科: ${subject}`);
      
      // 这里应该添加实际加载图表的代码，使用echarts等图表库
      // 例如：初始化echarts图表，根据examRecords数据渲染成绩趋势图等
    },

    goBack() {
      this.$router.push({ name: "Analysis" }); // 返回上一页
    },
    // 获取学生基本信息
    async fetchStudentInfo() {
      if (!this.studentId) {
        console.warn("没有学生ID，无法获取学生信息");
        return;
      }
      
      try {
        console.log(`开始获取学生ID为[${this.studentId}]的基本信息`);
        
        // 0. 首先尝试直接通过API获取单个学生信息
        try {
          console.log("尝试通过API直接获取学生信息");
          const token = localStorage.getItem('token') || 
                      localStorage.getItem('accessToken') || 
                      localStorage.getItem('authToken') || 
                      localStorage.getItem('jwtToken');
          
          const studentResponse = await axios.get(`/api/student/${this.studentId}`, {
            headers: {
              'Authorization': token ? `Bearer ${token}` : ''
            }
          });
          
          console.log("直接获取学生信息响应:", studentResponse);
          
          if (studentResponse?.data?.data) {
            const studentData = studentResponse.data.data;
            this.studentName = studentData.name;
            this.studentClass = studentData.className || "未知班级";
            console.log(`通过API获取到学生信息: 姓名=${this.studentName}, 班级=${this.studentClass}`);
            return;
          }
        } catch (err) {
          console.log("通过API直接获取学生信息失败:", err);
        }
        
        // 1. 尝试从班级列表中查找学生信息
        if (this.classList && this.classList.length > 0) {
          console.log("尝试从班级列表中查找学生信息");
        for (const classData of this.classList) {
            try {
              console.log(`尝试从班级[${classData.id}:${classData.name || classData.className}]中查找学生`);
          const classStudents = await fetchStudentList(classData.id, 1, 100);
              if (classStudents && classStudents.data) {
                const studentsArray = classStudents.data.data || classStudents.data.students || [];
                if (Array.isArray(studentsArray)) {
                  const foundStudent = studentsArray.find(s => 
                    s.studentId === this.studentId || 
                    s.id === this.studentId || 
                    s.id === parseInt(this.studentId) || 
                    s.studentId === String(this.studentId)
                  );
            
            if (foundStudent) {
                    console.log(`在班级[${classData.id}]中找到学生:`, foundStudent);
              this.studentName = foundStudent.name;
                    this.studentClass = classData.name || classData.className;
                    console.log(`设置学生信息: 姓名=${this.studentName}, 班级=${this.studentClass}`);
                    return; // 找到了，结束查找
                  }
                }
              }
            } catch (err) {
              console.error(`从班级[${classData.id}]查找学生失败:`, err);
            }
          }
        }
        
        // 2. 尝试通过接口直接获取班级所有学生信息
        try {
          const studentsByClassResponse = await axios.get('/api/class-students', {
            params: { page: 1, size: 100 }
          });
          console.log("获取所有学生列表:", studentsByClassResponse);
          
          if (studentsByClassResponse?.data?.data && Array.isArray(studentsByClassResponse.data.data)) {
            const allStudents = studentsByClassResponse.data.data;
            const foundStudent = allStudents.find(s => 
              s.studentId === this.studentId || 
              s.id === this.studentId || 
              s.id === parseInt(this.studentId) || 
              s.studentId === String(this.studentId)
            );
            
            if (foundStudent) {
              console.log("在所有学生列表中找到学生:", foundStudent);
              this.studentName = foundStudent.name;
              
              // 尝试找到学生所在的班级
              if (foundStudent.classId && this.classList) {
                const studentClass = this.classList.find(c => c.id === foundStudent.classId);
                if (studentClass) {
                  this.studentClass = studentClass.name || studentClass.className;
                }
              } else {
                this.studentClass = foundStudent.className || "未知班级";
              }
              
              console.log(`设置学生信息: 姓名=${this.studentName}, 班级=${this.studentClass}`);
              return;
            }
          }
        } catch (err) {
          console.error("获取所有学生列表失败:", err);
        }
        
        // 3. 如果前面方法都未找到，尝试从考试记录中获取
        if (!this.studentName && this.examRecords && this.examRecords.length > 0) {
          console.log("尝试从考试记录中获取学生信息");
          // 考试记录中可能有一些学生信息
          const studentInfo = this.examRecords[0];
          if (studentInfo.student_name) {
            this.studentName = studentInfo.student_name;
            console.log(`从考试记录获取到学生姓名: ${this.studentName}`);
          }
        }
        
        // 如果经过所有尝试后仍没有获取到学生名称，设置为默认值
        if (!this.studentName) {
          this.studentName = `学生(ID:${this.studentId})`;
          console.log(`未找到学生名称，设置为默认值: ${this.studentName}`);
        }
        
        // 如果经过所有尝试后仍没有获取到班级，设置为默认值
        if (!this.studentClass) {
          this.studentClass = "未知班级";
          console.log(`未找到学生班级，设置为默认值: ${this.studentClass}`);
        }
      } catch (error) {
        console.error("获取学生信息失败:", error);
        // 设置默认值，确保UI不会显示空白
        if (!this.studentName) this.studentName = `学生(ID:${this.studentId})`;
        if (!this.studentClass) this.studentClass = "未知班级";
      }
    },
    // 添加格式化日期为字符串的方法
    formatDateToString(date) {
      if (!date) return '';
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    // 初始化教师信息 - 直接从登录信息获取学科
    async initTeacherInfo() {
      try {
        // 从路由参数获取教师学科（优先级最高）
        if (this.routeTeacherSubject) {
          this.teacherSubjectCode = this.routeTeacherSubject;
          console.log(`使用路由参数的教师学科: ${this.teacherSubjectCode}`);
          return;
        }
        
        // 从localStorage获取教师信息
        const teacherId = localStorage.getItem('teacherId');
        const teacherName = localStorage.getItem('teacherName');
        const teacherSubject = localStorage.getItem('teacherSubject'); // 直接获取学科
        
        console.log("从localStorage获取的教师信息:", { teacherId, teacherName, teacherSubject });
        
        // 设置教师姓名
        this.teacherName = teacherName;
        
        // 如果localStorage中已有学科信息，直接使用
        if (teacherSubject) {
          this.teacherSubjectCode = teacherSubject;
          console.log(`直接从localStorage获取到教师学科：${this.teacherSubjectCode}`);
          return;
        }
        
        // 否则尝试从后端获取
        if (teacherId) {
          this.teacherId = teacherId;
          await this.fetchTeacherInfo(teacherId);
        } else if (teacherName) {
          await this.fetchTeacherInfoByName(teacherName);
        } else {
          console.warn("未找到教师ID或姓名信息，无法获取学科信息");
        }
      } catch (error) {
        console.error("初始化教师信息失败:", error);
      }
    },
    
    // 根据教师ID获取教师信息
    async fetchTeacherInfo(teacherId) {
      // 如果已经有学科信息，则不需要再获取
      if (this.routeTeacherSubject || this.teacherSubjectCode) {
        console.log("已有教师学科信息，不再从API获取");
        console.log("当前routeTeacherSubject:", this.routeTeacherSubject);
        console.log("当前teacherSubjectCode:", this.teacherSubjectCode);
        return;
      }
      
      if (!teacherId) {
        console.warn("教师ID为空，无法获取教师信息");
        return;
      }
      
      try {
        console.log(`开始获取教师ID为[${teacherId}]的信息`);
        
        // 获取token
        const token = this.getAuthToken();
        
        // 尝试从localStorage获取
        const storedSubject = localStorage.getItem('teacherSubject');
        if (storedSubject) {
          this.teacherSubjectCode = storedSubject;
          console.log(`从localStorage获取到教师学科: ${this.teacherSubjectCode}`);
          return;
        }
        
        // 尝试教师API
        try {
          const response = await axios.get(`/api/teachers/teacher-id/${teacherId}`, {
            headers: {
              'Authorization': token ? `Bearer ${token}` : '',
              'Content-Type': 'application/json'
            }
          });
          
          console.log("教师API响应:", response);
          
          if (response.data && response.data.subject) {
            const rawSubject = response.data.subject;
            this.teacherSubjectCode = this.normalizeSubject(rawSubject);
            console.log(`从教师API获取到原始学科: ${rawSubject}`);
            console.log(`规范化后的学科代码: ${this.teacherSubjectCode}`);
            
            // 保存到localStorage以便后续使用
            localStorage.setItem('teacherSubject', this.teacherSubjectCode);
            return;
          } else {
            console.log("API响应中没有subject字段:", response.data);
          }
        } catch (error) {
          console.log(`API路径/api/teachers/teacher-id/${teacherId}失败:`, error);
          console.log("错误详情:", error.response ? error.response.data : error.message);
        }
        
        // 备选API路径
        try {
          const response = await axios.get(`/api/teacher/${teacherId}`, {
            headers: {
              'Authorization': token ? `Bearer ${token}` : '',
              'Content-Type': 'application/json'
            }
          });
          
          console.log("备选API响应:", response);
          
          if (response.data) {
            // 处理响应数据
            const data = response.data;
            let teacherData = null;
            
            if (data.status === "success" && data.data) {
              teacherData = data.data;
            } else if (data.code === 200 && data.data) {
              teacherData = data.data;
            } else {
              teacherData = data; // 直接使用响应数据
            }
            
            // 提取学科信息
            if (teacherData.subject) {
              this.teacherSubjectCode = this.normalizeSubject(teacherData.subject);
              console.log(`从备选API获取到教师学科: ${this.teacherSubjectCode}`);
              
              // 保存到localStorage以便后续使用
              localStorage.setItem('teacherSubject', this.teacherSubjectCode);
              return;
            }
          }
        } catch (error) {
          console.log(`备选API路径/api/teacher/${teacherId}失败`, error);
        }
        
        // 使用教师信息获取教师学科
        if (this.teacherName) {
          this.fetchTeacherInfoByName(this.teacherName);
        } else {
          // 如果所有API都失败，提示用户
          console.warn("所有API尝试都失败，无法获取教师学科信息");
        }
        
      } catch (error) {
        console.error("获取教师信息失败:", error);
      }
    },
    
    // 根据教师姓名获取教师信息
    async fetchTeacherInfoByName(teacherName) {
      if (!teacherName) {
        console.warn("教师姓名为空，无法获取教师信息");
        return;
      }
      
      try {
        console.log(`开始通过姓名[${teacherName}]获取教师信息`);
        
        // 获取token
        const token = this.getAuthToken();
        
        // 使用教师姓名API
        try {
          const response = await axios.get(`/api/teacher/by-name`, {
            params: { name: teacherName },
            headers: {
              'Authorization': token ? `Bearer ${token}` : '',
              'Content-Type': 'application/json'
            }
          });
          
          console.log("通过姓名获取教师信息响应:", response);
          
          if (response && response.data) {
            // 处理响应数据
            const data = response.data;
            let teacherData = null;
            
            if (data.status === "success" && data.data) {
              teacherData = data.data;
            } else if (data.code === 200 && data.data) {
              teacherData = data.data;
            } else {
              teacherData = data; // 直接使用响应数据
            }
            
            // 提取学科信息
            if (teacherData.subject) {
              this.teacherSubjectCode = this.normalizeSubject(teacherData.subject);
              console.log(`通过姓名API获取到教师学科: ${this.teacherSubjectCode}`);
              
              // 保存到localStorage以便后续使用
              localStorage.setItem('teacherSubject', this.teacherSubjectCode);
              
              // 如果获取到了教师ID，也保存起来
              if (teacherData.teacherId || teacherData.teacher_id) {
                const id = teacherData.teacherId || teacherData.teacher_id;
                localStorage.setItem('teacherId', id);
                this.teacherId = id;
                console.log(`保存教师ID: ${id}`);
              }
              
              return;
            }
          }
        } catch (error) {
          console.log("API路径/api/teacher/by-name失败", error);
        }
        
        // 备选API路径
        try {
          const response = await axios.get(`/api/search`, {
            params: { name: teacherName },
            headers: {
              'Authorization': token ? `Bearer ${token}` : '',
              'Content-Type': 'application/json'
            }
          });
          
          console.log("通过搜索API获取教师信息响应:", response);
          
          if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
            const teacherData = response.data[0]; // 取第一个匹配结果
            
            if (teacherData.subject) {
              this.teacherSubjectCode = this.normalizeSubject(teacherData.subject);
              console.log(`通过搜索API获取到教师学科: ${this.teacherSubjectCode}`);
              
              // 保存到localStorage
              localStorage.setItem('teacherSubject', this.teacherSubjectCode);
              
              // 如果获取到了教师ID，也保存起来
              if (teacherData.teacherId || teacherData.teacher_id) {
                const id = teacherData.teacherId || teacherData.teacher_id;
                localStorage.setItem('teacherId', id);
                this.teacherId = id;
                console.log(`保存教师ID: ${id}`);
              }
              
              return;
            }
          }
        } catch (error) {
          console.log("搜索API失败", error);
        }
        
        // 如果所有API都失败，提示用户
        console.warn("所有API尝试都失败，无法获取教师学科信息");
        this.$message.warning("无法获取您的学科信息，请重新登录");
        
      } catch (error) {
        console.error("通过姓名获取教师信息失败:", error);
        this.$message.error("获取教师学科信息失败，请重新登录");
      }
    },
    
    // 标准化学科代码
    normalizeSubject(subject) {
      if (!subject) {
        console.log("传入的学科为空，返回空字符串");
        return '';
      }
      
      // 转为小写
      const lowerSubject = String(subject).toLowerCase();
      console.log(`[normalizeSubject] 标准化学科输入: "${subject}", 转小写后: "${lowerSubject}"`);
      
      // 中文学科名称映射
      const zhSubjectMap = {
        '语文': 'chinese',
        '数学': 'math',
        '英语': 'english',
        '物理': 'physics',
        '化学': 'chemistry',
        '生物': 'biology',
        '政治': 'politics',
        '历史': 'history',
        '地理': 'geography'
      };
      
      // 如果是中文学科名称，转换为英文代码
      if (zhSubjectMap[subject]) {
        const result = zhSubjectMap[subject];
        console.log(`[normalizeSubject] 找到完全匹配的中文学科名称, 转换为: "${result}"`);
        return result;
      }
      
      // 检查经过转小写后的中文名称
      if (zhSubjectMap[lowerSubject]) {
        const result = zhSubjectMap[lowerSubject];
        console.log(`[normalizeSubject] 小写后匹配中文学科名称, 转换为: "${result}"`);
        return result;
      }
      
      // 已经是标准学科代码
      const validSubjects = ['chinese', 'math', 'english', 'physics', 'chemistry', 
                           'biology', 'politics', 'history', 'geography'];
      if (validSubjects.includes(lowerSubject)) {
        console.log(`[normalizeSubject] 已经是标准学科代码: "${lowerSubject}"`);
        return lowerSubject;
      }
      
      // 处理简写或部分匹配
      if (lowerSubject.includes('chin') || lowerSubject.includes('yuwen') || lowerSubject.includes('语文')) {
        console.log(`[normalizeSubject] 部分匹配语文/chinese`);
        return 'chinese';
      }
      if (lowerSubject.includes('math') || lowerSubject.includes('shuxue') || lowerSubject.includes('数学')) {
        console.log(`[normalizeSubject] 部分匹配数学/math`);
        return 'math';
      }
      if (lowerSubject.includes('eng') || lowerSubject.includes('yingyu') || lowerSubject.includes('英语')) {
        console.log(`[normalizeSubject] 部分匹配英语/english`); 
        return 'english';
      }
      if (lowerSubject.includes('phys') || lowerSubject.includes('wuli') || lowerSubject.includes('物理')) {
        console.log(`[normalizeSubject] 部分匹配物理/physics`);
        return 'physics';
      }
      if (lowerSubject.includes('chem') || lowerSubject.includes('huaxue') || lowerSubject.includes('化学')) {
        console.log(`[normalizeSubject] 部分匹配化学/chemistry`);
        return 'chemistry';
      }
      if (lowerSubject.includes('bio') || lowerSubject.includes('shengwu') || lowerSubject.includes('生物')) {
        console.log(`[normalizeSubject] 部分匹配生物/biology`);
        return 'biology';
      }
      if (lowerSubject.includes('poli') || lowerSubject.includes('zheng') || lowerSubject.includes('政治')) {
        console.log(`[normalizeSubject] 部分匹配政治/politics`);
        return 'politics';
      }
      if (lowerSubject.includes('hist') || lowerSubject.includes('lishi') || lowerSubject.includes('历史')) {
        console.log(`[normalizeSubject] 部分匹配历史/history`);
        return 'history';
      }
      if (lowerSubject.includes('geo') || lowerSubject.includes('dili') || lowerSubject.includes('地理')) {
        console.log(`[normalizeSubject] 部分匹配地理/geography`);
        return 'geography';
      }
      
      // 默认返回原值
      console.log(`[normalizeSubject] 无法匹配任何学科，返回原值: "${lowerSubject}"`);
      return lowerSubject;
    },
    
    // 修改为不使用默认学科或根据名称推断
    useDefaultSubject() {
      // 尝试从localStorage获取教师学科，如果有就使用
      const storedSubject = localStorage.getItem('teacherSubject');
      if (storedSubject) {
        this.teacherSubjectCode = storedSubject;
        console.log(`从localStorage获取到教师学科: ${this.teacherSubjectCode}`);
        return;
      }
      
      // 如果没有找到学科信息，返回空值
      this.teacherSubjectCode = '';
      console.log('无法确定教师学科，不再使用默认值');
    },
    
    // 处理编辑对话框中选择考试记录的变更
    handleEditExamRecordChange(row) {
      if (!row) return;
      
      this.currentEditExam = row;
      
      // 获取当前考试记录的日期，确保格式正确
      let examTime = row.examTime;
      
      // 如果日期不是YYYY-MM-DD格式，尝试格式化它
      if (examTime && typeof examTime === 'string' && !examTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
        try {
          const dateObj = new Date(examTime);
          if (!isNaN(dateObj.getTime())) {
            examTime = this.formatDateToString(dateObj);
          }
        } catch (e) {
          console.error("日期格式化错误:", e);
        }
      }
      
      // 填充表单
      this.examForm = {
        examName: row.examName,
        examTime: examTime,
        score: row[this.teacherSubject], // 获取当前教师学科的成绩
        remarks: row[`${this.teacherSubject}_remarks`] || "" // 获取特定学科的备注
      };
      
      console.log("已选择要编辑的考试记录:", this.examForm);
    },
    handleAiSend() {
      if (!this.aiInputMessage.trim()) return;
      
      // 检查学生是否已选择
      if (!this.studentId) {
        this.$message.warning("请先选择一名学生");
        return;
      }
      
      // 添加用户消息到对话框
      this.aiMessages.push({
        content: this.aiInputMessage,
        time: new Date().toLocaleString(),
        type: 'user'
      });
      
      // 滚动到底部
      this.$nextTick(() => {
        if (this.$refs.chatMessages) {
          this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
        }
      });
      
      // 保存用户输入并清空输入框
      const userQuestion = this.aiInputMessage;
      this.aiInputMessage = '';
      this.isLoading = true;
      
      // 准备发送给后端的数据
      const requestData = {
        studentInfo: {
          studentId: this.studentId,
          studentName: this.studentName,
          studentClass: this.studentClass
        },
        examRecords: this.examRecords || [], // 所有考试记录
        teacherSubject: this.teacherSubject, // 当前教师学科
        teacherSubjectName: this.teacherSubjectName, // 当前教师学科名称
        userQuestion: userQuestion // 用户提问内容
      };
      
      console.log("准备发送AI分析请求:", JSON.stringify(requestData));
      
      // 获取认证令牌
      const token = this.getAuthToken();
      
      // 确保baseURL是正确的
      const apiUrl = axios.defaults.baseURL || 'http://localhost:8080';
      console.log("当前API基础URL:", apiUrl);
      
      // 直接使用axios发送请求，方便调试
      axios.post(`${apiUrl}/api/teaching/ai-analysis`, requestData, {
        headers: {
          'Authorization': token ? `Bearer ${token}` : '',
          'Content-Type': 'application/json'
        }
      })
        .then(response => {
          console.log("AI分析响应成功:", response);
          
          if (response && response.data) {
            // 获取AI回复内容
            const aiContent = response.data.message || response.data.result || response.data.content || response.data;
            
            // 创建AI回复消息对象
            const aiMessage = {
              content: aiContent,
              time: new Date().toLocaleString(),
              type: 'ai',
              saved: false, // 初始未保存
              // 保存分析相关的元数据
              metadata: {
                studentId: this.studentId,
                studentName: this.studentName,
                studentClass: this.studentClass,
                teacherSubject: this.teacherSubject,
                teacherSubjectName: this.teacherSubjectName,
                userQuestion: userQuestion,
                timestamp: new Date().toISOString()
              }
            };
            
            // 添加AI回复到对话框
            this.aiMessages.push(aiMessage);
            
            // 保存最后一次分析结果
            this.lastAnalysisResult = aiMessage;
          } else {
            // 如果没有响应数据，显示错误消息
            this.aiMessages.push({
              content: "抱歉，AI分析返回为空，请稍后重试。",
              time: new Date().toLocaleString(),
              type: 'ai',
              saved: false
            });
          }
        })
        .catch(error => {
          console.error("AI分析请求失败:", error);
          console.error("请求配置:", error.config);
          console.error("响应状态:", error.response ? error.response.status : "无响应");
          console.error("响应数据:", error.response ? error.response.data : "无数据");
          
          // 测试API是否可访问
          axios.get(`${apiUrl}/api/teaching/ai-analysis/test`)
            .then(testResp => {
              console.log("API测试响应:", testResp.data);
            })
            .catch(testErr => {
              console.error("API测试失败:", testErr.response ? testErr.response.status : "无响应");
            });
          
          // 显示更详细的错误消息
          let errorMsg = "抱歉，AI分析请求失败：";
          
          if (error.response) {
            // 服务器响应了，但状态码不是2xx
            errorMsg += `服务器返回 ${error.response.status}`;
            if (error.response.data && error.response.data.message) {
              errorMsg += `，${error.response.data.message}`;
            } else if (error.response.data) {
              errorMsg += `，${JSON.stringify(error.response.data)}`;
            }
          } else if (error.request) {
            // 请求已发送但没有收到响应
            errorMsg += "未收到服务器响应，请检查服务器是否运行";
          } else {
            // 请求设置有问题
            errorMsg += `请求设置错误: ${error.message}`;
          }
          
          this.aiMessages.push({
            content: errorMsg,
            time: new Date().toLocaleString(),
            type: 'ai',
            saved: false
          });
        })
        .finally(() => {
          this.isLoading = false;
          
          // 滚动到底部
          this.$nextTick(() => {
            if (this.$refs.chatMessages) {
              this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
            }
          });
        });
    },

    // 保存分析结果到数据库
    saveAnalysisResult(message) {
      if (!message || message.saved) return;
      
      this.$confirm('确定要保存此分析结果吗?', '保存确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 准备保存的数据
        const saveData = {
          studentId: this.studentId,
          studentName: this.studentName,
          studentClass: this.studentClass,
          teacherSubject: this.teacherSubject,
          teacherSubjectName: this.teacherSubjectName,
          question: message.metadata ? message.metadata.userQuestion : '',
          answer: message.content,
          examRecords: this.examRecords.map(record => ({
            examName: record.examName,
            examTime: record.examTime,
            score: record[this.teacherSubject],
            remarks: record[`${this.teacherSubject}_remarks`] || ''
          }))
        };
        
        console.log("准备保存分析结果:", saveData);
        
        // 显示加载状态
        const loadingInstance = this.$loading({
          lock: true,
          text: '正在保存...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        // 调用保存API
        saveAiAnalysis(saveData)
          .then(response => {
            console.log("保存分析结果响应:", response);
            
            if (response && (response.data.status === 'success' || response.data.code === 200)) {
              // 标记消息为已保存
              message.saved = true;
              
              // 更新视图
              this.$forceUpdate();
              
              // 显示成功消息
              this.$message.success('分析结果已成功保存');
            } else {
              this.$message.error('保存分析结果失败: ' + (response.data.message || '未知错误'));
            }
          })
          .catch(error => {
            console.error("保存分析结果失败:", error);
            this.$message.error('保存分析结果失败: ' + (error.response?.data?.message || error.message || '未知错误'));
          })
          .finally(() => {
            // 关闭加载状态
            loadingInstance.close();
          });
      }).catch(() => {
        // 用户取消保存
        this.$message.info('已取消保存');
      });
    },

    // 改进 handleAiSend 旁边的一个方法，用于在用户点击预设问题时自动填充
    fillPresetQuestion(question) {
      this.aiInputMessage = question;
    },
    
    // 复制内容到剪贴板
    copyToClipboard(text) {
      navigator.clipboard.writeText(text)
        .then(() => {
          this.$message.success('已复制到剪贴板');
        })
        .catch(err => {
          console.error('复制失败:', err);
          this.$message.error('复制失败: ' + err);
        });
    },
  },
};
</script>

<style scoped>
.per-learn-case {
  padding: 20px;
  height: 100%;
  margin-top: 60px; /* 添加顶部边距，避免被导航栏遮挡 */
}

.back {
  margin-bottom: 20px;
  position: absolute;
  top: 80px; /* 调整位置，确保在导航栏下方 */
  left: 20px;
  z-index: 1000; /* 确保按钮在最上层 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 20px; /* 添加顶部边距，为返回按钮留出空间 */
}

.content {
  display: flex;
  height: calc(100vh - 200px);
}

.student-list {
  width: 300px;
  padding-right: 20px;
  border-right: 1px solid #eee;
}

/* 学生信息框样式 */
.student-info-box {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.info-title {
  font-size: 18px;
  font-weight: bold;
  color: #1b4380;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.student-info-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: bold;
  color: #606266;
  min-width: 70px;
}

.info-value {
  color: #333;
  flex: 1;
}

.student-details {
  flex: 1;
  padding-left: 20px;
  overflow-y: auto;
}

.student-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-section {
  margin-top: 20px;
}

.chart {
  height: 400px;
  margin-top: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

/* 考试记录区域样式 */
.exam-records-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.exam-records-section h4 {
  margin-bottom: 15px;
  color: #1b4380;
  font-size: 18px;
}

.no-data-message {
  padding: 20px;
  text-align: center;
  color: #909399;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 20px;
}

.el-table .el-table__body tr.highlighted {
  background-color: #ecf5ff;
}

.el-table .cell {
  text-align: center;
}

/* 对话框样式 */
.exam-dialog-content {
  margin-bottom: 20px;
  padding: 0 15px;
  max-height: 70vh;
  overflow-y: auto;
}

.exam-form {
  margin-bottom: 20px;
}

/* 添加考试记录列表样式 */
.exam-records-list {
  margin-bottom: 20px;
}

.exam-records-list h4 {
  margin-bottom: 15px;
  color: #1b4380;
  font-size: 16px;
}

.students-score-table {
  margin-top: 20px;
}

.students-score-table h4 {
  margin-bottom: 15px;
  font-size: 16px;
  color: #1b4380;
}

/* 添加自定义模态框样式 */
.custom-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000; /* 降低z-index，确保日期选择器弹出层能显示在上面 */
}

/* 为日期选择器添加自定义样式 */
:global(.date-picker-popper) {
  z-index: 3000 !important; /* 确保日期选择器弹出层的z-index高于模态框 */
}

/* 其他样式保持不变 */
.custom-modal-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 500px;
  max-width: 90%;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.custom-modal-header {
  padding: 20px 20px 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

.custom-modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.custom-modal-close {
  font-size: 20px;
  color: #909399;
  cursor: pointer;
}

.custom-modal-close:hover {
  color: #409EFF;
}

.custom-modal-footer {
  padding: 10px 20px 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

/* 添加推荐考试名称样式 */
.suggested-names {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.suggested-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.suggested-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  cursor: pointer;
}

.suggested-tag:hover {
  opacity: 0.8;
}

/* 优化表单样式 */
.exam-form .el-form-item {
  margin-bottom: 18px;
}

/* 添加日期调试区域样式 */
.selected-date-debug {
  margin-top: 10px;
  padding: 5px 10px;
  background-color: #ecf8ff;
  border-radius: 4px;
  color: #409EFF;
  font-size: 13px;
}

.selected-date-debug p {
  margin: 0;
}

/* 添加日期格式提示样式 */
.date-format-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.2;
}

/* 添加考试名称错误提示样式 */
.exam-name-error {
  color: #F56C6C;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  margin-top: 4px;
}

/* 添加AI分析助手样式 */
.ai-chat-container {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  height: 500px;
  background-color: #fff;
  overflow: hidden;
}

.ai-chat-header {
  background: linear-gradient(135deg, #409EFF, #1989fa);
  color: white;
  padding: 12px 15px;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.ai-chat-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.ai-chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.ai-welcome-message {
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  border-left: 4px solid #409EFF;
}

.ai-welcome-message p {
  margin-top: 0;
  font-weight: bold;
  color: #333;
}

.ai-welcome-message ul {
  padding-left: 20px;
}

.ai-welcome-message li {
  margin-bottom: 8px;
  color: #606266;
}

.ai-message {
  margin-bottom: 15px;
  padding: 12px 15px;
  border-radius: 8px;
  position: relative;
  max-width: 90%;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.ai-message.user {
  background-color: #ecf5ff;
  margin-left: auto;
  border-bottom-right-radius: 0;
  color: #303133;
}

.ai-message.ai {
  background-color: white;
  margin-right: auto;
  border-bottom-left-radius: 0;
  color: #303133;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border-left: 3px solid #67c23a;
}

.ai-message-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}

.ai-message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  text-align: right;
}

.ai-save-action {
  margin-top: 10px;
  text-align: right;
}

.ai-saved-tag {
  margin-top: 10px;
  text-align: right;
}

.ai-loading {
  display: flex;
  align-items: center;
  color: #909399;
  font-style: italic;
  padding: 10px;
}

.ai-loading .dot-1, .ai-loading .dot-2, .ai-loading .dot-3 {
  animation: loading-dots 1.4s infinite;
  opacity: 0;
  font-size: 20px;
  line-height: 10px;
}

.ai-loading .dot-2 {
  animation-delay: 0.2s;
}

.ai-loading .dot-3 {
  animation-delay: 0.4s;
}

@keyframes loading-dots {
  0% { opacity: 0; }
  25% { opacity: 0.3; }
  50% { opacity: 0.6; }
  75% { opacity: 1; }
  100% { opacity: 0; }
}

.ai-chat-input {
  padding: 15px;
  border-top: 1px solid #ebeef5;
  display: flex;
  background-color: white;
}

.ai-chat-input .el-input {
  margin-right: 10px;
}

.ai-chat-input .el-textarea__inner {
  border-radius: 18px;
  padding: 10px 15px;
  resize: none;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s;
}

.ai-chat-input .el-textarea__inner:focus {
  box-shadow: 0 0 0 1px #409EFF inset;
}

.ai-quick-questions {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
}

.quick-title {
  font-size: 14px;
  color: #606266;
  margin: 0 0 8px 0;
}

.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-buttons .el-button {
  margin-right: 8px;
  margin-bottom: 8px;
  transition: all 0.3s;
}

.quick-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 改进日期选择器样式 */
/* 这里是CSS注释，不要使用双斜杠注释 */
</style>

<style>
/* 全局样式，确保日期选择器正确显示 */
.el-picker-panel {
  z-index: 3000 !important;
}
</style>